package com.cookor.poi.modules.weixin.open;

import com.alibaba.druid.support.json.JSONUtils;
import com.cookor.poi.modules.weixin.account.PlatformAccount;
import com.cookor.poi.modules.weixin.account.ThirdPlatform;
import com.cookor.poi.modules.weixin.account.WeixinException;
import com.cookor.poi.utils.CacheFactory;
import com.google.common.collect.Maps;
import com.xiaoleilu.hutool.http.HttpUtil;
import com.xiaoleilu.hutool.json.JSONObject;
import com.xiaoleilu.hutool.json.JSONUtil;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description: TODO
 * @author: scott
 * @date: 2021年05月18日 15:06
 */
public class WxOpenUtil {

    protected static Logger logger = LoggerFactory.getLogger(WxOpenUtil.class);

    /**
     * 第三方平台appId
     */
    private static final String PLATFORM_APP_ID = "wx1db31fec7b602c66";

    /**
     * 第三方平台 secret
     */
    private static final String PLATFORM_APP_SECRET = "8c8ce818418d6e787e1c912462e4ab43";

    /**
     * 第三方平台 消息加解密Key
     */
    private static final String PLATFORM_AES_KEY = "bzE15ryvsyiinR8iW6NFStYrXiyVCH199D6CXCFR9Vh";

    /**
     * 第三方平台 消息校验Token
     */
    private static final String PLATFORM_COMPONENT_TOKEN = "uoSS25xL2IMw2ZVdCS9H3LHxdFdP4OI4";

    public static String parsePequest(String timeStamp, String nonce, String msgSignature, String postData) {
        logger.debug("==============================开始授权事件接收URL=================================");
        try {
            //这个类是微信官网提供的解密类,需要用到消息校验Token 消息加密Key和服务平台appid
            WXBizMsgCrypt pc = new WXBizMsgCrypt(PLATFORM_COMPONENT_TOKEN, PLATFORM_AES_KEY, PLATFORM_APP_ID);
            String xml = pc.decryptMsg(msgSignature, timeStamp, nonce, postData);
            Map<String, String> result = WXXmlToMapUtil.xmlToMap(xml);// 将xml转为map
            logger.info("map:"+result.toString());
            String componentVerifyTicket = MapUtils.getString(result, "ComponentVerifyTicket");
            logger.info("====================授权票据【ComponentVerifyTicket】：【" + componentVerifyTicket + "】====================");
            if (StringUtils.isNotEmpty(componentVerifyTicket)) {
                // 存储平台授权票据,保存ticket
                CacheFactory.put("account:ticket:"
                                + ThirdPlatform.COMPONENTAPPID, componentVerifyTicket);
                String verifyTicket = CacheFactory.get("account:ticket:"
                        + ThirdPlatform.COMPONENTAPPID).toString();
                logger.info("====================授权票据【ComponentVerifyTicket_缓存】：【" + verifyTicket + "】====================");
            } else {
                throw new RuntimeException("微信开放平台，第三方平台获取【验证票据】失败");
            }
        } catch (AesException e) {
            e.printStackTrace();
        }
        logger.info("==============================结束授权事件接收URL=================================");
        return "success";
    }

//    public static String getAccessToken() throws WeixinException {
//        String cachename = "openaccesstoken";
//        String cachekey = PLATFORM_APP_ID;
//        String accessToken = null;
//        Map<String, String> map = (Map<String, String>) CacheFactory
//                .get(cachename, cachekey);
//        if (isUseCache(map)) {
//            String url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";
//            Map<String, Object> params = new ConcurrentHashMap<>();
//            params.put("component_appid", PLATFORM_APP_ID);
//            params.put("component_appsecret", PLATFORM_APP_SECRET);
//            params.put("component_verify_ticket", CacheFactory.get("openwxticket", PLATFORM_APP_ID).toString());
//            JSONObject jsonObject = httpPost(url, JSONUtils.toJSONString(params));
//            accessToken = jsonObject.getStr("component_access_token");
//            String expires_in = jsonObject.getStr("expires_in");
//            map = Maps.newConcurrentMap();
//            map.put("component_access_token", accessToken);
//            map.put("expires_in", expires_in);
//            if (StringUtils.isBlank(accessToken)) {
//                String msg = "获取开放平台token失败, 请稍后重试！ 开放平台返回原始数据为: 错误代码-"
//                        + jsonObject.getStr("errcode") + "，错误信息-"
//                        + jsonObject.getStr("errmsg");
//                throw new WeixinException(msg);
//            }
//            CacheFactory.put(cachename, cachekey, map,
//                    7000, -1);
//            return accessToken;
//        }
//        return map.get("component_access_token");
//    }

//    public static void getAuthInfo(String code)throws Exception{
//        Map<String, Object> params = new ConcurrentHashMap<>();
//        params.put("component_appid", PLATFORM_APP_ID);
//        params.put("authorization_code", code);
//        String url = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token="+PlatformAccount.getComponentAccesstoken();
//        JSONObject jsonObject = httpPost(url, JSONUtils.toJSONString(params));
//        jsonObject = jsonObject.getJSONObject("authorization_info");
//        String authorizer_appid = jsonObject.getStr("authorizer_appid");
//        String authorizer_refresh_token = jsonObject.getStr("authorizer_refresh_token");
//        if(StringUtils.isBlank(authorizer_appid) || StringUtils.isBlank("authorizer_refresh_token")){
//            throw new Exception("授权请求异常！");
//        }
//        CacheFactory.put("auth:refresh:token:"+authorizer_appid, authorizer_refresh_token);
//    }

//    public static String getAuthAccessToken(String appid) throws WeixinException {
//        String cachename = "authtoken";
//        String cachekey = appid;
//        String accessToken = null;
//        Map<String, String> map = (Map<String, String>) CacheFactory
//                .get(cachename, cachekey);
//        if (isUseCache(map)) {
//            String refreshToken = CacheFactory.get("authrefreshtoken", appid).toString();
//            String url = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=" + getAccessToken();
//            Map<String, Object> params = new ConcurrentHashMap<>();
//            params.put("component_appid", PLATFORM_APP_ID);
//            params.put("authorizer_appid", appid);
//            params.put("authorizer_refresh_token", refreshToken);
//            JSONObject jsonObject = httpPost(url, JSONUtils.toJSONString(params));
//            String token = jsonObject.getStr("authorizer_access_token");
//            String refresh = jsonObject.getStr("authorizer_refresh_token");
//            String expires_in = jsonObject.getStr("expires_in");
//            map = Maps.newConcurrentMap();
//            map.put("authorizer_access_token", token);
//            map.put("expires_in", expires_in);
//
//            CacheFactory.put(cachename, appid, map,
//                    7000, -1);
//            CacheFactory.put("authrefreshtoken", appid, refresh);
//            logger.info("获取到authorizer_access_token=" + token);
//            return token;
//        }
//        return map.get("authorizer_access_token");
//    }
//
    public static String getOauthUrl()throws Exception{
        String componentAccesstoken = PlatformAccount.getComponentAccesstoken();
        String url = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token="+componentAccesstoken;
        Map<String, Object> params = new ConcurrentHashMap<>();
        params.put("component_appid", PLATFORM_APP_ID);
        JSONObject jsonObject = httpPost(url, JSONUtils.toJSONString(params));
        String code = jsonObject.getStr("pre_auth_code");
        if(StringUtils.isBlank(code)){
            logger.error("jo:"+jsonObject.toString());
            throw new Exception("code异常");
        }
//        String auth_url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=" +
//                PLATFORM_APP_ID +
//                "&pre_auth_code=" +
//                code +
//                "&redirect_uri=" +
//                "xxxx&auth_type=xxx"
        String auth_url = "https://mp.weixin.qq.com/safe/bindcomponent?action=bindcomponent&no_scan=1&" +
                "component_appid=" + PLATFORM_APP_ID +
                "&pre_auth_code=" + code +"&redirect_uri=" + "https://zx.nthink.cn/openwx/oauth/success" +
                "&auth_type=1#wechat_redirect";
        return auth_url;
    }
//
//    public static boolean isUseCache(Map<String, String> map) {
//        long TIMESTAMP = System.currentTimeMillis() / 1000;
//        return map == null || StringUtils.isBlank(map.get("value"))
//                || Integer.valueOf(map.get("expire")) < TIMESTAMP;
//    }
//
//
//    public static JSONObject httpPost(String url, Map<String, Object> paramMap) {
//        logger.debug("request：" + url);
//        logger.debug("参数" + paramMap);
//        String result = HttpUtil.post(url, paramMap);
//        logger.debug("response1：\n" + result);
//        return JSONUtil.parseObj(result);
//    }
//
    public static JSONObject httpPost(String url, String data) {
        logger.debug("request：" + url);
        logger.debug("参数:" + data);
        String result = HttpUtil.post(url, data);
        logger.debug("response：\n" + result);
        return JSONUtil.parseObj(result);
    }

}
